import Mock, { mock } from 'mockjs'

// 获取 mock.Random 对象
const Random = Mock.Random

let newsList = []

// mock新闻数据，包括新闻标题title、内容content、创建时间createdTime
const produceNewsData = function () {
    newsList = []
    for (let i = 0; i < 2; i++) {
        let newNewsObject = {
            id:i,
            title: Random.ctitle(), // Random.ctitle( min, max ) 随机产生一个中文标题，长度默认在3-7之间
            content: Random.cparagraph(), // Random.cparagraph(min, max) 随机生成一个中文段落，段落里的句子个数默认3-7个
            createdTime: Random.date() // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd；
        }
        newsList.push(newNewsObject)
    }
    return newsList
}
produceNewsData();

let qyrurl = '/mock/news'
function qryNews(ops){
    console.log(ops) // 先看一下这个ops是什么

    let url = qyrurl + '?';
    let params = ops.url.replace(url,'');

    
    console.log(params);

    let inparams = params.split("&");
    console.log(inparams);

    debugger
    let thisNewsList = newsList;
    for(let i =0 ;i <inparams.length;i++){
        let param = inparams[i].split("=");
        
        console.log(param);

        if(param.length==2 && param[1]){
            // if(param[0]=='title')
            debugger
            thisNewsList = thisNewsList.filter(item=>{
                return item[param[0]]==param[1]
            });

        }
    }
    return thisNewsList;
}

// 请求该url，就可以返回newsList
Mock.mock(RegExp(qyrurl), ops=>qryNews(ops)) // 后面讲这个api的使用细节



// Mock.mock('/mock/addNew', ops => { // 拦截ajax请求，调用函数
//     console.log(ops) // 先看一下这个ops是什么 
//     //{
//     //     "url": "/mock/addNew",
//     //     "type": "POST",
//     //     "body": "{\"id\":11111,\"title\":\"yxy\",\"content\":\"yxy yxy yx y yxy xy xy yx \",\"createdTime\":\"2021-10-11\"}"
//     // }
//     newsList.push(JSON.parse(ops.body))
//     // debugger
//     return newsList
//    })
function addnews(mckops) {
    let params = JSON.parse(mckops.body);
    params.id = newsList.length+100
    newsList.push(params);

    return newsList;
}
Mock.mock('/mock/addNew', ops=>addnews(ops))

const delurl ='/mock/deleteNew/';
const delNew = function(mockops){
    // {
    //     "url": "/mock/deleteNew/0",
    //     "type": "DELETE",
    //     "body": null
    // }
        console.log(mockops);
        
        let ids= mockops.url.replace(delurl,'').split('/');
        if(ids.length) {
            let id = ids[0];
            // let aa = newsList.map(aa=>{
            //     if(aa.id!=id){
            //         return aa;
            //     };
            // })

            let bb = newsList.filter(aa=>aa.id!=id);
            newsList = bb;
        }
        // debugger;
        return newsList;
        // let params = JSON.parse(mckops.body);

}

//正则表达式
// Mock.mock(/\/mock\/deleteNew\//,ops=>delNew(ops))
// Mock.mock(/\/mock\/deleteNew/,ops=>delNew(ops))

Mock.mock(RegExp(delurl),ops=>delNew(ops))

